﻿/*
 * Created by SharpDevelop.
 * User: Heikki
 * Date: 9.11.2007
 * Time: 15:19
 */

using System;
using System.Data.SQLite;

namespace notebooklet
{
	public class Contact : IDataObj
	{
		private SQLiteConnection db;
		
		private int    id;
		private string name;
		private string email;
		private string notes;
		
		public int     Id {
			get { return id; }
			set { id = value; }
		}
		public string  Name {
			get { return name; }
			set { name = value; }
		}
		public string  Email {
			get { return email; }
			set { email = value; }
		}
		public string  Notes {
			get { return notes; }
			set { notes = value; }
		}
		
		public Contact(SQLiteConnection db,
					int id,
		            string name,
		            string email,
		            string notes) {
			this.db = db;
			this.Id = id;
			this.Name = name;
			this.Email = email;
			this.Notes = notes;
		}
		
		override public string ToString() {
			return "id: " + this.Id + "\r\n" + 
				"Name: " + this.Name + "\r\n" +
				"Email: " + this.Email + "\r\n" + 
				"Notes: " + this.Notes + "\r\n";
		}
		

		public bool load() { return true; }
		public bool save() {
			SQLiteCommand cmd = db.CreateCommand();
			SQLiteDataReader data;
			
			cmd.CommandText = "SELECT count(*) as count FROM contacts WHERE id=" + this.Id + ";";
			data = cmd.ExecuteReader();
			data.Read();
			
			if ( 1 == System.Convert.ToInt32(data["count"].ToString()) ) {
				data.Close();
				
				// TODO: http://xkcd.com/327/	
				cmd.CommandText = "UPDATE contacts SET " +
					              "name = \"" + this.Name + "\", " +
								  "email = \"" + this.Email + "\", " +
								  "notes = \"" + this.Notes + "\" " +
								  "WHERE id = \"" + this.Id + "\";";
				cmd.ExecuteNonQuery();
				return true;
			}
			data.Close();
			
			// TODO: http://xkcd.com/327/
			cmd.CommandText = "INSERT INTO contacts VALUES(" +
							  this.Id + ", " +
							  "\"" + this.Name + "\", " +
					          "\"" + this.Email + "\", " +
							  "\"" + this.Notes + "\");";
			cmd.ExecuteNonQuery();
			return true;
		}
		
		// TODO: Aluksi copypaste, myöhemmin jaettuna koodina
		public int getNextId() {
			SQLiteCommand cmd = db.CreateCommand();
			SQLiteDataReader data;
			
			cmd.CommandText = "SELECT id FROM contactsSeq";
			data = cmd.ExecuteReader();
			data.Read();
			
			int nextId = System.Convert.ToInt32(data["id"].ToString());
			
			cmd.CommandText = "UPDATE contactsSeq SET id = id + 1";
			cmd.ExecuteNonQuery();
			
			return nextId;
		}
	}
}
